﻿using System;
using System.Globalization;

namespace NazTek.Extension.Clr4
{
    /// <summary> 
    /// Extends Byte
    /// </summary> 
    /// <remarks></remarks> 
    public static class ByteExtension
    {
        /// <summary> 
        /// Converts to an item in the generically specified Enum type, based on value match 
        /// </summary> 
        /// <typeparam name="T">The enum type to search for the corresponding item match</typeparam> 
        /// <param name="enumValue">Corresponding byte value of the enum item to search for</param> 
        /// <returns>The matched enum item</returns> 
        /// <remarks></remarks> 
        /// <example>Sample below shows how to use the method.
        /// <code>
        ///     // context byte enum
        ///     public enum MyEnum : byte
        ///     {
        ///         One,
        ///         Two,
        ///         Three
        ///     }
        ///     // context int enum
        ///     public enum MyOtherEnum
        ///     {
        ///         One,
        ///         Two,
        ///         Three
        ///     }
        ///     // context class
        ///     public class MyClass{}
        ///     
        ///     // sample
        ///     // excepion - "Target type, MyClass, is not an enum"
        ///     Enum itm = Convert.ToByte(10).ToEnum&lt;MyClass&gt;(true);
        ///     // excepion - "The specified item, 10, is not defined in MyEnum Enum type"
        ///     itm = Convert.ToByte(10).ToEnum&lt;MyEnum&gt;();
        ///     // exception - MyOtherEnum's underlying type is not System.Byte.  Either change the type of the generic to an enum 
        ///     // with underlying type of System.Byte or change the underlying type of the value, 2
        ///     itm = Convert.ToByte(2).ToEnum&lt;MyOtherEnum&gt;();
        ///     // success - Three
        ///     itm = Convert.ToByte(2).ToEnum&lt;MyEnum&gt;();
        /// </code>
        /// </example>
        public static T ToEnum<T>(this byte enumValue)
        {
            Parameter.ValidateToEnum<byte, T>(enumValue, Common.QTN_BYTE);
            return (T)Enum.Parse(typeof(T), enumValue.ToString(CultureInfo.InvariantCulture));
        }
    }
}